
package com.be.beadmin.device.impl;

import cn.hutool.core.date.DateTime;
import com.be.beadmin.basicData.entity.Role;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.RoleRepository;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.entity.EhsInfo;
import com.be.beadmin.device.entity.EhsInfo_;
import com.be.beadmin.device.entity.InspectPlan;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.EhsInfoMapperEx;
import com.be.beadmin.device.repository.EhsInfoRepository;
import com.be.beadmin.device.service.EhsInfoService;
import com.be.beadmin.device.dto.input.EhsInfoDto;
import com.be.beadmin.device.dto.output.EhsInfoEx;
import com.be.beadmin.device.mapper.EhsInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author zty
* @date 2023-08-13
**/
@Service
@RequiredArgsConstructor
public class EhsInfoServiceImpl implements EhsInfoService {

    @Autowired
    private  EhsInfoRepository ehsInfoRepository;
    @Autowired
    private  EhsInfoMapper ehsInfoMapper;
    @Autowired
    private  EhsInfoMapperEx ehsInfoExMapper;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    @Override
    public Page<EhsInfoEx> getEhsInfoByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<EhsInfo> page = ehsInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(EhsInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(EhsInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<EhsInfoEx> page1 = page.map(ehsInfoExMapper::toEntity);
            return page1;

    }

    @Override
    public void addEhsInfo(EhsInfoDto ehsInfoDto) {
            EhsInfo result = ehsInfoRepository.findEhsInfoByIdAndDelete(ehsInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("EhsInfo不存在,请重新查询");
            }
            Date date = ehsInfoDto.getCheckDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //生成巡检单号，保证巡检单号唯一
            List<EhsInfo> ehsInfoList = ehsInfoRepository.findAll();
            List<Date> stringList = ehsInfoList.stream().map(EhsInfo::getCheckDate).collect(Collectors.toList());
            int num = 1;
            for (Date d : stringList){
                if(ObjectUtil.isNotEmpty(d)){
                    String s1 = simpleDateFormat.format(date);
                    String s2 = simpleDateFormat.format(d);
                    if(s1.equals(s2)){
                        num++;
                    }
                }
            }
            int year = date.getYear()+1900;
            int month = date.getMonth()+1;
            int day = date.getDate();
            ehsInfoDto.setCheckId("EHS"+year+month+day+"_"+num);
            EhsInfo ehsInfo = ehsInfoMapper.toEntity(ehsInfoDto);
            EhsInfo save = ehsInfoRepository.save(ehsInfo);

        //-----------------------------------------------------------------------
        //发消息放最后
        //EHS巡检的ehs专员checkBy  发给  EHS巡检指定的处理人HandleBy，通知类型
            //定义消息实体notifyInfo
            NotifyInfo notifyInfo =new NotifyInfo();
            notifyInfo.setModuleName("设备管理");
            notifyInfo.setFuncName("EHS巡检");

            notifyInfo.setNotifyDesc("EHS巡检单编码为["+save.getCheckId()+"],EHS巡检单已创建");
            notifyInfo.setNotifyType("通知");

            notifyInfo.setSenderName(save.getCheckBy());

            notifyInfo.setSendTime(save.getCreateTime());
            notifyInfo = notifyInfoRepository.save(notifyInfo);

            //调用发消息的接口
            notifyTemplateInfoService.sendNotify(notifyInfo,-1,save.getHandleBy(),null);

            //发消息放最后
        //-----------------------------------------------------------------------
    }

    @Override
    public void updateEhsInfo(EhsInfoDto ehsInfoDto) {
            EhsInfo ehsInfo = ehsInfoRepository.findEhsInfoById(ehsInfoDto.getId());
            ehsInfo = ehsInfoMapper.toEntity(ehsInfoDto);
            ehsInfoRepository.save(ehsInfo);
    }


    @Override
    public void delEhsInfo(String id) {
        EhsInfo ehsInfo = ehsInfoRepository.findEhsInfoById(id);
        ehsInfo.setDelete(1);
        ehsInfoRepository.save(ehsInfo);
    }

    @Override
    public void delEhsInfos (List<String> ids) { }

    @Override
    public List<String> getEhsCommissioners() {
        Role role = roleRepository.findRoleByNameAndDelete("EHS专员" , 0);
        String roleId = role.getId();
        List<String> userIds = userRepository.findUserIdsByRoleId(roleId);
        List<String> nameList = new ArrayList<>();
        for(String userId : userIds){
            nameList.add(userRepository.findUserNameById(userId));
        }
        return nameList;
    }


    @Override
    public List<String> getEhsHandlers() {
        Role role = roleRepository.findRoleByNameAndDelete("EHS处理人员" , 0);
        String roleId = role.getId();
        List<String> userIds = userRepository.findUserIdsByRoleId(roleId);
        List<String> nameList = new ArrayList<>();
        for(String userId : userIds){
            nameList.add(userRepository.findUserNameById(userId));
        }
        return nameList;
    }
}